package middlewares

import (
	"gozeroStandalone/utils"
	"net/http"
	"strconv"
	"strings"

	"github.com/zeromicro/go-zero/rest/httpx"
)

/*
 +----------------------------------------------------------------------
 + Title        : frontendAuth
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2019-08-08
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : 前端认证中间件
 +----------------------------------------------------------------------
*/

type FrontendAuthMiddleware struct {
	Secret string
}

/**
 * 用户认证
 *
 * @param http.HandlerFunc next ------------------------------必传
 * @return http.HandlerFunc
 * @author huwl
 */
func (auth *FrontendAuthMiddleware) AuthUser(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		authorization := r.Header.Get("Authorization")
		if authorization == "" || len(strings.Split(authorization, " ")) != 2 {
			httpx.OkJsonCtx(r.Context(), w, utils.ErrorOutput("authorization token is empty"))
			return
		}

		token := strings.Split(authorization, " ")[1]
		uid, err := utils.ParseToken(token)
		if err != nil {
			httpx.OkJsonCtx(r.Context(), w, utils.ErrorOutput(err.Error()))
			return
		}

		r.Header.Set("uid", strconv.Itoa(int(uid)))
		next(w, r)
	}
}
